package com.q.tqb.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.q.tqb.base.AppConst;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * @author Administrator
 *         微信登录分享回调
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    //WXCallbackActivity
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        IWXAPI api = WXAPIFactory.createWXAPI(this, AppConst.WEIXIN_APP_ID, true);
        api.handleIntent(this.getIntent(), this);
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    //app发送消息给微信，处理返回消息的回调
    @Override
    public void onResp(BaseResp resp) {

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (RETURN_MSG_TYPE_SHARE == resp.getType()) {
                    showToast("分享失败");
                    finish();
                } else {
                    showToast("授权登录失败");
                    finish();
                }
                break;
            case BaseResp.ErrCode.ERR_OK:
                Intent intent;
                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_LOGIN:
                        //拿到了微信返回的code,请求服务器登录
                        String code = ((SendAuth.Resp) resp).code;
                        intent = new Intent();
                        intent.setAction(AppConst.WX_LOGIN);
                        intent.putExtra("code", code);
                        WXEntryActivity.this.sendBroadcast(intent);
                        finish();
                        break;
                    case RETURN_MSG_TYPE_SHARE:
                        showToast("分享成功");
                        intent = new Intent();
                        intent.setAction(AppConst.WX_SHARE);
                        WXEntryActivity.this.sendBroadcast(intent);
                        finish();
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }


    public void showToast(String content) {
        Toast.makeText(WXEntryActivity.this, content, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }
}

